package com.eptok.weixin.util;

import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Arrays;

import yspay.express.store.WxStore;

/**
 * 首次成为开发者验证工具类<br><br>
 *
 *将token、timestamp、nonce三个参数进行字典序排序,
 *将三个参数字符串拼接成一个字符串进行sha1加密,
 *开发者获得加密后的字符串可与signature对比，标识该请求来源于微信.  
 * @author haisong
 *
 */
public class SignUtil {
	
	/**
	 * 首次连接时验证签名
	 * @param signature 加密的签名
	 * @param timeStamp 时间戳
	 * @param nonce 随机数
	 * @return
	 * @throws UnsupportedEncodingException 
	 */
	public static boolean checkSigntaur(String signature,String timeStamp,String nonce) throws UnsupportedEncodingException {
		
		//对token、timestamp、nonce按字典排序
		String[] paramArr = new String [] {WxStore.getToken(),timeStamp,nonce}; 
		Arrays.sort(paramArr);
		
		//将排序后的结果拼接为一个字符串
		String content = paramArr[0].concat(paramArr[1]).concat(paramArr[2]);
		
		String ciphertext = null;
		
		try {
			MessageDigest md = MessageDigest.getInstance("SHA-1");
			
			byte[] digest = md.digest(content.getBytes("UTF-8"));
			
			ciphertext = byteToStr(digest);
			
		} catch (NoSuchAlgorithmException e) {

			e.printStackTrace();
		}
		
		return ciphertext != null?ciphertext.equals(signature.toUpperCase()):false;
	}
	
	
	/**
	 * 将字节数组转换成十六进制字符串
	 * @param byteArray
	 * @return
	 */
	private static String byteToStr(byte[] byteArray) {
		String str = "";
		for (int i = 0; i < byteArray.length; i++) {
			str += byteToHexStr(byteArray[i]); 
		}
		return str;
	}
	
	
	
	private static String byteToHexStr(byte mByte) {
		
		char[] digit = {'0','1','2','3','4','5','6','7','8','9','A','B','C','D','E','F'};
		char[] tempArr = new char[2];
		tempArr[0] = digit[(mByte >>> 4) & 0X0F];
		tempArr[1] = digit[mByte & 0X0F];
		
		String str = new String(tempArr);
		return str;
	}
	
	public static String sha1(String str) throws UnsupportedEncodingException {
		try {
			MessageDigest digest = java.security.MessageDigest.getInstance("SHA-1"); // 如果是SHA加密只需要将"SHA-1"改成"SHA"即可
			digest.update(str.getBytes("UTF-8"));
			byte messageDigest[] = digest.digest();
			// Create Hex String
			StringBuffer hexStr = new StringBuffer();
			// 字节数组转换为 十六进制 数
			for (int i = 0; i < messageDigest.length; i++) {
				String shaHex = Integer.toHexString(messageDigest[i] & 0xFF);
				if (shaHex.length() < 2) {
					hexStr.append(0);
				}
				hexStr.append(shaHex);
			}
			return hexStr.toString();

		} catch (NoSuchAlgorithmException e) {
			e.printStackTrace();
		}
		return null;
	}
}
